package coursedesign.lancelot.sharingaccountbook.Activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;

import coursedesign.lancelot.sharingaccountbook.R;
import coursedesign.lancelot.sharingaccountbook.Utils.AesImp;
import coursedesign.lancelot.sharingaccountbook.Utils.CodeUtils;
import coursedesign.lancelot.sharingaccountbook.Utils.ReUtil;
import coursedesign.lancelot.sharingaccountbook.Utils.UserCodeGenerator;
import coursedesign.lancelot.sharingaccountbook.Utils.simpleDialog;
import coursedesign.lancelot.sharingaccountbook.dataAccess.AccountbookDao;
import coursedesign.lancelot.sharingaccountbook.dataAccess.AccountbookMembershipDao;
import coursedesign.lancelot.sharingaccountbook.dataAccess.LocalDatabaseAccess;
import coursedesign.lancelot.sharingaccountbook.domain.Accountbook;
import coursedesign.lancelot.sharingaccountbook.domain.AccountbookMembership;
import coursedesign.lancelot.sharingaccountbook.domain.User;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {
    private final String  REMOTEIP = "http://118.24.187.42:8080";
    private final User loginUser = new User();
    private Button lo_bt_register;
    private Button login;
    private ImageButton lo_IMB_check;
    private EditText lo_Edt_Check;
    private EditText lo_Edt_Uname;
    private EditText lo_Edt_Psd;
    private String userName,pwd,encodePwd;
    private Handler myHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            switch (msg.what)
            {
                case -1:
                    toast("登录失败!");
                    loginUser.setIdentity("loginFailed");
                    break;
                case 1:
                    SharedPreferences.Editor editor = getSharedPreferences("userdata",MODE_PRIVATE).edit();
                    editor.clear();
                    editor.putString("userName",userName);
                    editor.putString("encodePwd",encodePwd);
                    editor.apply();


                    Intent intent = new Intent(LoginActivity.this, DisplayActivity.class);
                    intent.putExtra("loginUser",loginUser);
                    startActivity(intent);
                    finish();
            }
            return true;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //初始化控件
        iniUI();

        Bitmap bp = new CodeUtils().createBitmap();
        lo_IMB_check.setImageBitmap(bp);

        //点击更换验证码
        lo_IMB_check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bitmap bp = new CodeUtils().createBitmap();
                lo_IMB_check.setImageBitmap(bp);
            }
        });

        lo_bt_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开注册对话框
                Intent intent = new Intent(getApplicationContext(),RegisterActivity.class);
                startActivity(intent);
            }
        });


        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userName = lo_Edt_Uname.getText().toString();
                pwd = lo_Edt_Psd.getText().toString();
                String ck = new CodeUtils().getCode();
                String checkNumber = lo_Edt_Check.getText().toString();
                if (!checkNumber.equals(ck)){
                    toast("验证码错误！");
                }else {
                    if (reCheck(userName,pwd)) {
                        remoteLoginTestify(userName, pwd);
                    }
                }



            }
        });


    }
    private boolean reCheck(String Name,String Pwd){
        boolean rst = true;
        ReUtil reHandler = new ReUtil();
        reHandler.useDefaultNamePattern();
        if (!reHandler.matched(Name)){
            toast("用户名字段有非法内容");
            return false;
        }
        reHandler.useDefaultPwdPattern();
        if (!reHandler.matched(Pwd)){
            toast("密码字段有非法内容");
            return false;
        }
        return rst;
    }




    private void iniUI() {
        lo_bt_register = (Button)findViewById(R.id.lo_bt_register);
        lo_IMB_check = (ImageButton)findViewById(R.id.lo_IMB_check);
        lo_Edt_Check = (EditText)findViewById(R.id.lo_Edt_Check);
        login = (Button)findViewById(R.id.login);
        lo_Edt_Uname = (EditText)findViewById(R.id.lo_Edt_Uname);
        lo_Edt_Psd = (EditText)findViewById(R.id.lo_Edt_Psd);
    }

    private void remoteLoginTestify(String userName,String pwd){
        encodePwd = AesImp.encode(pwd);
        String url = REMOTEIP+"/accountBookServer/login?" +
                "uName="+userName+
                "&pwd="+encodePwd;
        Log.d("okhttp", "remoteLoginTestify: "+url);
        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("connection time out");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonStr = response.body().string();
                JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                String state = jsonObject.getString("identity");
                Message msg = new Message();
                if (state.equals("loginFailed")){
                    msg.what = -1;
                    myHandler.sendMessage(msg);
                    return;
                }

                loginUser.setUserId(jsonObject.getInteger("userId"));
                loginUser.setUserName(jsonObject.getString("userName"));
                loginUser.setNickName(jsonObject.getString("nickName"));
                loginUser.setIdentity(jsonObject.getString("identity"));
                loginUser.setPhoneNumber(jsonObject.getString("phoneNumber"));
//                msg.what = 10;
//                AccountbookMembershipDao abm = new AccountbookMembershipDao(LocalDatabaseAccess.initDatabaseAccess());
//                if (abm.query(null,null,null,null,null,null,null).size() == 0){
                msg.what = 1;
//                }
                myHandler.sendMessage(msg);
            }
        });
    }


    public void toast(String content){
        Toast.makeText(getApplicationContext(),content,Toast.LENGTH_LONG).show();
    }
}
